package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.constants.RedisConstant;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    @Override
    public List<ShopType> getTypeList() {

        String key = RedisConstant.SHOP_TYPE_CACHE + "getTypeList";

        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();

        Map<Object, Object> map = opsForHash.entries(key);

        List<ShopType> list = new LinkedList<>();
//
//      如果redis中查询到了店铺分类
        if(!map.isEmpty()){
            log.info("redis中查询到店铺分类+++++防止查询数据库");
            List<ShopType> finalList = list;
            map.forEach((k, v)->{
//
                finalList.add(JSONUtil.toBean((String)v, ShopType.class));
            });
            return finalList;
        }

//        如果redis中没有查询到店铺分类

        list = this.query().orderByAsc("sort").list();
        if(list.isEmpty()){
            throw new RuntimeException("店铺分类不存在");
        }
//        数据库中查询到以后，信息插入redis中
        list.forEach(type -> {
            opsForHash.put(key, type.getName(), JSONUtil.toJsonStr(type));
        });

        return list;
    }
}
